import { Container } from 'pixi.js'
import { loadBase64, imageToSprite } from "../util.js";

export class Tile {
  constructor(resource, stage) {
    this.resource = resource;
    this.stage = stage;

    this.layers = {
      0: [],
      1: [],
      2: [],
      3: [],
      4: [],
      5: [],
      6: [],
      7: [],
    };

    // 保存所有,Obj的Container
    this.containerArr = [];
  }

  /**
   * 
   * @param {object} Map
   * @public 
   */
  async load(Map) {
    // const resource = this.resource;
    // const result = new Set();
    // Object.keys(Map).forEach((key) => {
    //   if (Number.isInteger(Number(key)) && Map[key].info.tS) {
    //     const tS = Map[key].info.tS;
    //     result.add(tS);
    //   }
    // });
    // for (let tS of result) {
    //   await resource.load("Map/Tile", `./Map/Tile/${tS}.img.json`);
    // }
    await this.dealWithTile(Map);
  }

  /**
   * @public
   */
  draw(layer) {
    const stage = this.stage;
    const containerArr = this.containerArr;
    const layers = this.layers;

    let container = new Container();
    container.sortableChildren = true;
    container.zIndex = layer;
    layers[layer].forEach(sprite => {
      container.addChild(sprite);
    })
    stage.addChild(container);
    containerArr.push(container);
  }

  destroy() {
    const stage = this.stage;
    const containerArr = this.containerArr;
    const layers = this.layers;

    containerArr.forEach(container => {
      stage.removeChild(container);
    })
    for (let i = 0; i < 7; i++) {
      layers[i].length = 0;
    }
    containerArr.length = 0;
  }

  /**
   * 
   * @param {object} Map
   * @private 
   */
  async dealWithTile(Map) {
    const resource = this.resource;
    const layers = this.layers;

    for (let i = 0; i < 7; i++) {
      if (!Map[i].tile) {
        continue;
      }
      for (let item of Object.values(Map[i].tile)) {
        const Tile = resource.Content.Map.Tile[Map[i].info.tS];
        const { x, y, no, u, zM, z } = item;
        const { origin, value } = Tile[u][no];
        let tile = await loadBase64(value);
        let sprite = imageToSprite(tile);
        sprite.x = x - origin.x;
        sprite.y = y - origin.y;
        sprite.zIndex = Number(z) === 0 ? Number(zM) : Number(z);
        layers[i].push(sprite);
      }
    }
  }
}